package com.jiamao.goplay.ui.user.vm;

import android.app.Application;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.PaifItme;
import com.jiamao.goplay.bean.PlaceWantGoItem;
import com.jiamao.goplay.bean.res.ResMatch;
import com.jiamao.goplay.bean.res.ResPaifList;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.MatchFragment;
import com.jiamao.goplay.util.GsonUtil;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.MessageDialog;
import com.tamsiree.rxkit.view.RxToast;

import java.io.Serializable;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;

/**
 * 邀请我的
 */
public class UserPaifVM extends BaseViewModel<DataRepository> {

    private int page = 1;
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public ObservableField<Integer> emptyVisble = new ObservableField<>(View.GONE);

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Boolean> pSwitchEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> refreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> refreshNums = new SingleLiveEvent<>();
        public SingleLiveEvent<String> startChat = new SingleLiveEvent<>();

    }

    public UserPaifVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);
        //从本地取得数据绑定到View层

//        for (int i=0;i<10;i++){
//            MultiItemViewModel item = new UserPaifItemVM(this);
//            item.multiItemType("image");
//            observableList.add(item) ;
//        }


    }




    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();
                itemBinding.set(BR.viewModel, R.layout.user_paif_item_layout);
            // itemBinding.set(BR.viewModel, R.layout.msg_home_item_layout);

        }
    });



    public void getDataList(int i){
        if (i == 0 ){
            page = 0;
        }
        page++;
        BaseSubscriber subscription = new BaseSubscriber<BaseRep<ResPaifList>>() {

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                uc.refreshEvent.setValue(0);
                e.printStackTrace();
                RxToast.showToastShort("网络出现故障");
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onNext(BaseRep<ResPaifList> baseRep) {
                super.onNext(baseRep);
                uc.refreshEvent.setValue(0);
                // dismissDialog();
                // dialog.dismiss();
                //保存账号密码
                if (baseRep.isOk()){
                    if (i == 0){
                        observableList.clear();
                        if (baseRep.getData().getPairList().size() == 0 ){
                            emptyVisble.set(View.VISIBLE);
                        }
                    }
                    uc.refreshNums.setValue(baseRep.getData().getPairNum());
                    for (int i=0;i<baseRep.getData().getPairList().size();i++){
                        PaifItme itemData =  baseRep.getData().getPairList().get(i);
                        KLog.d("html itemData"+itemData);
                        UserPaifItemVM item = new UserPaifItemVM(UserPaifVM.this,itemData);
                        item.multiItemType("image");
                        observableList.add(item) ;
                    }
                }else {
                    RxToast.showToastShort(baseRep.getMsg());
//
                }
            }
        };

        model.getApi().getPairList(page)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(subscription);



    }



    public void startChat(String uid){
        uc.startChat.setValue(uid);
    }


    public void jieshouyaoqing(String id,UserPaifItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().acceptInvite(id)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResMatch>>() {
                    @Override
                    public void onNext(BaseRep<ResMatch> baseRep) {

                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.updateypd();
                            Bundle bd= new Bundle();
                            bd.putString("data", GsonUtil.toJson(baseRep.getData()));
                            startContainerActivity(MatchFragment.class.getCanonicalName(),bd);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }





    public void jiechuyaoqing(String id,UserPaifItemVM vm){


        //uc.pSwitchEvent.setValue();
        model.getApi().delInvite(id)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {
                        dismissDialog();
                        if (baseRep.isOk()){
                            observableList.remove(vm);
                            //  vm.updateypd();
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }


    public void jiechupd(String uid,UserPaifItemVM vm){
        //uc.pSwitchEvent.setValue();
        showjiechuDialog(uid,vm);

    }
    public void showjiechuDialog(String uid,UserPaifItemVM vm){
        MessageDialog.build((AppCompatActivity) AppManager.getAppManager().currentActivity())
                .setStyle(DialogSettings.STYLE.STYLE_IOS)
                .setTitle("你确定要和 "+vm.name.get()+" 解除配对关系吗?")
                .setMessage("")
                .setOkButton("确定", new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        model.getApi().relieveRelation(uid)
                                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                                .compose(RxUtils.schedulersTransformer())  // 线程调度
                                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(Disposable disposable) throws Exception {
                                        //   uc.pSwitchEvent.setValue(1);
                                        showDialog();
                                        // dialog.show();
                                    }
                                })
                                .subscribe(new BaseSubscriber<BaseRep>() {
                                    @Override
                                    public void onNext(BaseRep baseRep) {

                                        super.onNext(baseRep);
                                        dismissDialog();
                                        if (baseRep.isOk()){
                                            Messenger.getDefault().send(uid,"jiechu");
                                            observableList.remove(vm);
                                            //  vm.updateypd();
                                        }else {
                                            RxToast.showToastShort(baseRep.getMsg());
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        dismissDialog();
                                        //   uc.pSwitchEvent.setValue(2);
                                        e.printStackTrace();
                                        RxToast.showToastShort("网络出现故障");
                                    }

                                    @Override
                                    public void onComplete() {
                                        //   dismissDialog();
                                    }

                                });
                        //AppApplication.getInstance().startLogins();
                        return false;
                    }

                }).setCancelButton("取消", new OnDialogButtonClickListener() {
            @Override
            public boolean onClick(BaseDialog baseDialog, View v) {

                //AppApplication.getInstance().startLogins();
                return false;
            }

        })
                .show();
    }
}
